/**
 * @Description:
 * @Author bianpengfei
 * @create 2021/6/23 14:45
 */
const CracoLessPlugin = require('craco-less')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const path = require('path')
const fs = require('fs')
const webpack = require('webpack')
const postcssNormalize = require('postcss-normalize')
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent')

const isEnvProduction = process.env.NODE_ENV === 'production'
const isEnvDevelopment = process.env.NODE_ENV === 'development'
const publicPath = isEnvProduction ? '/fr/h5-template' : '/'
const buildPath = (process.env.BUILD_PATH = 'dist')
const lessRegex = /\.less$/
const lessModuleRegex = /\.module\.less$/

// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor, preProcessorOptions = {}) => {
  const loaders = [
    isEnvDevelopment && require.resolve('style-loader'),
    isEnvProduction && {
      loader: MiniCssExtractPlugin.loader
    },
    {
      loader: require.resolve('css-loader'),
      options: cssOptions
    },
    {
      loader: require.resolve('postcss-loader'),
      options: {
        ident: 'postcss',
        plugins: () => [
          require('postcss-flexbugs-fixes'),
          require('postcss-preset-env')({
            autoprefixer: {
              flexbox: 'no-2009'
            },
            stage: 3
          }),
          postcssNormalize()
        ],
        sourceMap: isEnvDevelopment
      }
    }
  ].filter(Boolean)
  if (preProcessor) {
    loaders.push(
      {
        loader: require.resolve('resolve-url-loader'),
        options: {
          sourceMap: isEnvDevelopment,
          root: path.resolve(__dirname, 'src')
        }
      },
      {
        loader: require.resolve(preProcessor),
        options: {
          sourceMap: true,
          ...preProcessorOptions
        }
      }
    )
  }
  return loaders
}

module.exports = {
  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: { '@primary-color': '#1DA57A' },
            javascriptEnabled: true
          }
        }
      }
    },
    {
      plugin: {
        overrideWebpackConfig: ({ webpackConfig, cracoConfig, pluginOptions, context: { env, paths } }) => {
          webpackConfig.output = {
            ...webpackConfig.output,
            filename: 'js/[name].[hash].js',
            path: path.resolve(__dirname, buildPath),
            chunkFilename: 'js/[name].[hash].js',
            publicPath: publicPath,
            libraryTarget: 'umd',
            umdNamedDefine: true,
            globalObject: 'window'
          }

          webpackConfig.devtool = isEnvDevelopment ? 'cheap-module-eval-source-map' : false
          webpackConfig.module.rules.push(
            {
              test: lessModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 3,
                  sourceMap: isEnvDevelopment,
                  modules: {
                    getLocalIdent: getCSSModuleLocalIdent
                  }
                },
                'less-loader',
              ),
              sideEffects: true
            }
          )

          fs.writeFileSync(path.resolve(__dirname, './webpack.config.json'), JSON.stringify(webpackConfig, null, 2))
          return webpackConfig
        }
      },
      options: {}
    }
  ],
  webpack: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    },
    plugins: {
      add: [] /* An array of plugins */,
      remove: [] /* An array of plugin constructor's names (i.e. "StyleLintPlugin", "ESLintWebpackPlugin" ) */
    }
    // devtool: 'cheap-module-eval-source-map',
  }
}
